import {
  _decorator,
  RigidBody2D,
  PolygonCollider2D,
  Contact2DType,
  Collider2D,
  IPhysics2DContact,
} from 'cc';
import { ZombieBase } from './ZombieBase';
import { EventBus, TYPE } from '../Utils/EventBus';

const { ccclass } = _decorator;

@ccclass('NormalZombie')
export class NormalZombie extends ZombieBase {
  isDeath: boolean = false;

  protected onLoad(): void {
    this.init();
    const rb = this.getComponent(RigidBody2D);
    if (!rb) return;

    const col = this.getComponent(PolygonCollider2D);
    if (col) {
      col.sensor = false; // 必须 false 才能触发子弹 sensor
      col.apply();
      col.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }
    this.playAction('run')

    // EventBus.on(TYPE.DEBUG_ZOMBIE_RUN,()=>{
    //   this.playAction('run')
    // })
    // EventBus.on(TYPE.DEBUG_ZOMBIE_EAT,() => {
    //   this.playAction('attack')
    // })
    // EventBus.on(TYPE.DEBUG_ZOMBIE_DYING,()=>{
    //   this.playAction('dying')
    // })
    // EventBus.on(TYPE.DEBUG_ZOMBIE_DIE,() =>{
    //   this.playAction('die')
    // })
  }

  update(dt: number) {
    if (!this.isLoad) return;
    if (this._currentAction ==='attack') {
      this.attack(dt)
    } else {
      this.moveForward(dt);
    }
  }

  receivedAttackByBullet(cb: () => void) {
    this.hp -= 10;
    if ((this.hp / this.maxHp) * 100 <= 50) {
      this.playAction('dying');
    }
    if (this.hp <= 0) {
      this.speed = 0;
      this.playAction('die');
      cb();
    }
  }

  onBeginContact(
    self: Collider2D,
    other: Collider2D,
    contact: IPhysics2DContact
  ) {
    switch (other.node.name) {
      case 'bullet':
        if (!this.isDeath) {
          this.receivedAttackByBullet(() => {
            this.isDeath = true;
          });
        }
        break;
    }
  }
}
